<template>
  <div class="app-container">
    <el-dialog title="选择服务" :visible.sync="open" width="50%" append-to-body>
      <el-row :gutter="20">
        <!-- <el-col :span="6" >
          <el-card class="box-card">            

            <el-table
              v-loading="loading"
              :data="categoryList"
              row-key="id" 
              :default-expand-all="false"
              highlight-current-row
              :height="400"
              :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
              @row-click="handleCategoryRowClick"
            >
              <el-table-column label="类目名称" prop="name" >
                <template slot-scope="scope">
                  {{scope.row.name}}
                 
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col> -->
        <el-col :span="24" >
          <el-card class="box-card">
            <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          
            <el-form-item label="项目名称" prop="name">
              <el-input
                v-model="queryAttrParams.name"
                placeholder="请输入项目名称"
                clearable
                size="small"
                @keyup.enter.native="handleAttrQuery"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleAttrQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetAttrQuery">重置</el-button>
            </el-form-item>
          </el-form>

          <el-table v-loading="attrLoading" :data="attributeList"  @selection-change="handleSelectionChange" >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="编号" align="center" prop="id" />
            <el-table-column label="项目名称" align="left" prop="name" width="150" show-overflow-tooltip/>
            <el-table-column label="单位" align="center" prop="unit" />
           
            <el-table-column label="指导价" align="center" prop="price" />
            <el-table-column label="指导价浮动" align="center" prop="floatPrice" />
            <el-table-column label="下单价" align="center" prop="costPrice" />
            <el-table-column label="下单价浮动" align="center" prop="costFloatPrice" />
           
           
          </el-table>
          
          <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryAttrParams.pageNum"
            :limit.sync="queryAttrParams.pageSize"
            @pagination="getAttributeList"
          />
          </el-card>
          
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCategory, getCategory, delCategory, addCategory, updateCategory, exportCategory } from "@/api/business/category";
import { listselectAttribute, getAttribute, delAttribute, addAttribute, updateAttribute, exportAttribute } from "@/api/business/attribute";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ImageUpload from '@/components/ImageUpload';
import Editor from '@/components/Editor';
export default {
  name: "Category",
  components: {
    ImageUpload,
    Treeselect,
    Editor
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      attrLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 服务类目表格数据
      categoryList: [],
      attributeList: [],
      // 服务类目树选项
      categoryOptions: [],
      // 分类-规格属性表格数据
      categorySpecList: [],
      categorySpecValueList: [],
      // 选中数组
      ids: [],
      selectList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      currentSpecRow: null,
      // 子表选中数据
      checkedCategorySpec: [],
      // 子表选中数据
      checkedCategoryCert: [],
      // 分类-证书关联表格数据
      categoryCertList: [],
      attrCategorySpecList: [],
      attrSpecValueList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      total: 0,
      attrOpen: false,
      unitOptions: [],
      certOptions: [],
      // 查询参数
      queryParams: {
        name: null,
        keywords: null,
        description: null,
        parentId: null,
        level: null,
      },
      queryAttrParams: {
        pageNum: 1,
        pageSize: 5,
        categoryId: null,
        name: null,
        value: null
      },
      
      clickRow: null,
      // 表单参数
      form: {},
      attrform: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "类目名称不能为空", trigger: "blur" }
        ],
        
      },
      costPricePersonRate: null,
      costPriceCompanyRate: null,
      pricePayRate: null,
      firstUpdate: false,
      firstUpdate1: false
    };
  },
 
  created() {
    
    this.getDicts("tb_unit_type").then(response => {
      this.unitOptions = response.data;
    });
    this.getDicts("tb_cert_type").then(response => {
      this.certOptions = response.data;
    });
    this.getConfigKey("cost_price.person.rate").then(response => {
      this.costPricePersonRate = response.msg || 0.10;
    });
    this.getConfigKey("cost_price.company.rate").then(response => {
      this.costPriceCompanyRate = response.msg || 0.15;
    });
    this.getConfigKey("price.pay.rate").then(response => {
      this.pricePayRate = response.msg || 0.70;
    });
  },
  activated(){
    this.selectList = [];
    
  },
  methods: {
    init(limitType){
      this.open = true;
      this.selectList = [];
      this.attributeList = [];
      this.queryAttrParams.categoryId = limitType;
      this.getAttributeList();
    },
   
    /** 查询服务类目列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then(response => {
        this.categoryList = this.handleTree(response.data, "id", "parentId");
        this.loading = false;
      });
    },
    /** 查询服务分类参数列表 */
    getAttributeList() {
      // if (!this.clickRow.id) {
      //   return;
      // }
      this.attrLoading = true;
      // this.queryAttrParams.categoryId = this.clickRow.id;
      listselectAttribute(this.queryAttrParams).then(response => {
        this.attributeList = response.rows;
        this.total = response.total;
        this.attrLoading = false;
      });
    },
    /** 转换服务类目数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
	/** 查询服务类目下拉树结构 */
    getTreeselect() {
      listCategory().then(response => {
        this.categoryOptions = [];
        const data = { id: 0, name: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "id", "parentId");
        this.categoryOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        keywords: null,
        description: null,
        parentId: null,
        iconUrl: null,
        picUrl: null,
        level: null,
        sort: null,
        status: '1'
      };
      this.categorySpecValueList = [];
      this.categorySpecList = [];
      this.categoryCertList = [];
      this.resetForm("form");
    },
    // 表单重置
    resetAttr() {
      this.attrform = {
        id: null,
        name: null,
        value: null,
        unit: null,
        price: null,
        costPrice: null,
        hasNum: '1',
        detail: null,
        limitUser: '0',
        hot: '0'
      };
      this.resetForm("attrform");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 搜索按钮操作 */
    handleAttrQuery() {
      this.getAttributeList();
    },
    /** 搜索按钮操作 */
    resetAttrQuery() {
      this.queryAttrParams.name = "";
      this.getAttributeList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleAttribute(){
      if (!this.clickRow) {
        this.msgError("请先选择服务分类");
        return;
      }
      this.reset();
      this.attrOpen = true;
      this.queryAttrParams.categoryId = this.clickRow.id;
      this.attrform = {
        categoryId: this.clickRow.id,
        id: null,
        name: null,
        value: null,
        unit: null,
        detail: null,
        price: null,
        costPrice: null,
        hasNum: '1',
        hot: '0',
        limitUser: '0',
        status: '1',
        minNumber: '1'
      };
      getCategory(this.clickRow.id).then(response => {

        this.attrCategorySpecList = response.data.categorySpecList;
        
      });
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.parentId = row.id;
      } else {
        this.form.parentId = 0;
      }
      this.open = true;
      this.title = "添加服务类目";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.parentId = row.id;
      }
      getCategory(row.id).then(response => {
        this.form = response.data;
        this.categorySpecList = this.form.categorySpecList;
        this.categoryCertList = this.form.categoryCertList;
        this.open = true;
        this.title = "修改服务类目";
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.selectList = selection;
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 提交按钮 */
    submitForm() {
      if (!this.selectList) {
        this.msgError("请选择至少一条记录");
        return;
      }
      this.open = false;
      this.$emit("finishSelected", this.selectList);      
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除服务类目编号为"' + row.id + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCategory(row.id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
   
    /** 提交按钮 */
    submitAttrForm() {
      console.log(this.attrCategorySpecList)
      this.$refs["attrform"].validate(valid => {
        if (valid) {
          this.attrform.attrSpecValueList = this.attrCategorySpecList.map(a => {
            return {
              spec: a.name,
              value: a.value
            }
          });
          if (this.attrform.id != null) {
            updateAttribute(this.attrform).then(response => {
              this.msgSuccess("修改成功");
              this.attrOpen = false;
              this.getAttributeList();
              this.resetAttr();
            });
          } else {
            addAttribute(this.attrform).then(response => {
              this.msgSuccess("新增成功");
              this.attrOpen = false;              
              this.getAttributeList();
              this.resetAttr();
              
            });
          }
        }
      });
    },
    /** 修改按钮操作 */
    handleAttrUpdate(row) {  
      this.firstUpdate = true;    
      this.firstUpdate1 = true;    
      getCategory(row.categoryId).then(response => {
        let specList = response.data.categorySpecList;
        specList.forEach(a => {
          let val = row.attrSpecValueList.find(b => b.spec == a.name);
          a.value = val?.value;
        });
        this.attrCategorySpecList = specList;
        getAttribute(row.id).then(res => {
          this.attrform = res.data; 
          
          this.attrOpen = true;  
        });
      });  
    },
    /** 删除按钮操作 */
    handleAttrDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除服务分类参数编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delAttribute(ids);
        }).then(() => {
          this.getAttributeList();
          this.msgSuccess("删除成功");
        })
    },
    // 取消按钮
    cancelAttr() {
      this.attrOpen = false;
      this.reset();
    },
    handleCategoryRowClick(row) {
      this.clickRow = row;
      this.getAttributeList();
    },
    /** 分类-规格属性序号 */
    rowCategorySpecIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 分类-规格属性添加按钮操作 */
    handleAddCategorySpec() {
      let obj = {};
      obj.name = "";
      obj.specValueList = [];
      this.categorySpecList.push(obj);
      this.categorySpecValueList = [];
    },
    /** 分类-规格属性删除按钮操作 */
    handleDeleteCategorySpec() {
      if (this.checkedCategorySpec.length == 0) {
        this.$alert("请先选择要删除的分类-规格属性数据", "提示", { confirmButtonText: "确定", });
      } else {
        this.categorySpecList = this.categorySpecList.filter(a=>a != this.checkedCategorySpec[0]);
      }
    },
    /** 单选框选中数据 */
    handleCategorySpecSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.categorySpec.clearSelection();
        this.$refs.categorySpec.toggleRowSelection(selection.pop());
      } else {
        this.checkedCategorySpec = selection;
      }
    },
    /** 分类-证书关联序号 */
    rowCategoryCertIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 分类-证书关联添加按钮操作 */
    handleAddCategoryCert() {
      let obj = {};
      obj.certName = "";
      this.categoryCertList.push(obj);
    },
    /** 分类-证书关联删除按钮操作 */
    handleDeleteCategoryCert() {
      if (this.checkedCategoryCert.length == 0) {
        this.$alert("请先选择要删除的分类-证书关联数据", "提示", { confirmButtonText: "确定", });
      } else {
        this.categoryCertList = this.categoryCertList.filter(a=>a != this.checkedCategoryCert[0]);
      }
    },
    /** 单选框选中数据 */
    handleCategoryCertSelectionChange(selection) {
      if (selection.length > 1) {
        this.$refs.categoryCert.clearSelection();
        this.$refs.categoryCert.toggleRowSelection(selection.pop());
      } else {
        this.checkedCategoryCert = selection;
      }
    },
    addNewSpecValueRow(row){
      console.log(row)
      this.currentSpecRow = row;
      if (row.specValueList && row.specValueList.length > 0) {
        this.categorySpecValueList = row.specValueList;
      } else {
        this.categorySpecValueList = [{
          value: ""
        }];
        row.specValueList = this.categorySpecValueList;
        
      }
    },
    
    handleSpecValueAdd(row){
      this.categorySpecValueList.push({
        value: ""
      });
      this.currentSpecRow.specValueList = this.categorySpecValueList;
    },
    handleSpecValueDelete(row){
      this.categorySpecValueList = this.categorySpecValueList.filter(a=>a !=row);
      this.currentSpecRow.specValueList = this.categorySpecValueList;
    },
  }
};
</script>
<style scoped>
  .el-button + .el-button {
      margin-left: 4px;
  }
  .el-radio{
    margin-right: 0px;
  }
</style>
